package com.cyh.nio;

import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * selector的使用
 * */
public class SelectorDemo01 {

    public static void main(String[] args) throws Exception {

        //创建selector
        Selector selector = Selector.open();

        //通道
        ServerSocketChannel socketChannel = ServerSocketChannel.open();

        //必须是非阻塞的
        socketChannel.configureBlocking(false);

        //绑定连接
        socketChannel.bind(new InetSocketAddress(9999));

        //将通道注册到选择器中
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);


        //查询已经就绪通道操作
        Set<SelectionKey> selectionKeys = selector.selectedKeys();

        //遍历集合
        Iterator<SelectionKey> iterator = selectionKeys.iterator();
        while (iterator.hasNext()) {
            SelectionKey key = iterator.next();
            //判断key的就绪状态
            if(key.isAcceptable()) {

            } else if(key.isConnectable()) {

            } else if(key.isReadable()) {

            } else if(key.isWritable()) {

            }
            iterator.remove();
        }
    }
}
